<template>
    <div class="layout">
        <!-- 左侧导航栏 -->
        <div class="left-nav">
            <div class="nav-title">
                <span class="nav-text">标签分组</span>
                <el-tooltip content="添加分组" effect="dark" placement="top">
                    <el-icon
                        v-auth="'ADD_CHILD_GROUP'"
                        color="#FF6B00"
                        class="plus-icon"
                        @click="addGroup(false, firstId)"
                        ><plus
                    /></el-icon>
                </el-tooltip>
            </div>
            <div class="groups block">
                <el-input v-model="filterText" class="search_group" placeholder="请输入分组名称" />
                <el-scrollbar wrap-class="tree-scrollbar" :height="treeHeight">
                    <el-tree
                        ref="treeRef"
                        class="filter-tree"
                        node-key="id"
                        :data="groupData.userAllTagNameList"
                        :props="defaultProps"
                        :filter-node-method="filterNode"
                        :default-expand-all="true"
                        @node-click="nodeClick">
                        <template #default="{ data }">
                            <div
                                v-if="!['全部分组', '默认分组'].includes(data.name)"
                                class="hover-text"
                                @mouseover="mouseOver(data)"
                                @mouseleave="mouseLeave(data)">
                                <div :class="selectId == data.id ? 'hover-detail-color' : 'hover-detail'">
                                    {{ data.name }}
                                </div>
                                <el-tooltip
                                    placement="right"
                                    effect="light"
                                    :hide-after="0"
                                    :offset="0"
                                    @show="mouseOver2(data)"
                                    @hide="mouseLeave2(data)">
                                    <template #content>
                                        <el-link
                                            v-auth="'EDIT_CHILD_GROUP'"
                                            class="link-text"
                                            :underline="false"
                                            type="primary"
                                            @click="addGroup(true, data)"
                                            >编辑</el-link
                                        ><br />
                                        <el-link
                                            v-auth="'DEL_CHILD_GROUP'"
                                            class="link-text"
                                            :underline="false"
                                            type="primary"
                                            @click="removeGroup(data)"
                                            >删除</el-link
                                        ><br />
                                    </template>
                                    <span class="icon-span">
                                        <el-icon color="#FF6B00" class="hover-icon">
                                            <more-filled />
                                        </el-icon>
                                    </span>
                                </el-tooltip>
                            </div>
                            <template v-else>
                                <div class="hover-text">
                                    <div :class="selectId == data.id ? 'hover-detail-color' : 'hover-detail'">
                                        {{ data.name }}
                                    </div>
                                </div>
                            </template>
                        </template>
                    </el-tree>
                </el-scrollbar>
            </div>
        </div>
        <!-- 添加分组标签 -->
        <Dialog :app-dialog="appDialog">
            <el-form
                ref="ruleFormRef"
                :model="addGroupingForm"
                :rules="rules"
                label-width="120px"
                class="demo-ruleForm">
                <el-form-item label="分组名称" prop="name">
                    <el-input
                        v-model="addGroupingForm.name"
                        placeholder="请输入分组名称"
                        maxlength="15"
                        show-word-limit
                        clearable></el-input>
                </el-form-item>
            </el-form>
        </Dialog>
        <!-- 删除弹框 -->
        <ZWDeletdialog ref="groupDialogRef" @submit="delBtn" />
    </div>
</template>

<script setup lang="ts">
import { ref, watch, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElTree, ElForm } from 'element-plus';
import Dialog from '@/components/Dialog.vue';
import ZWDeletdialog from './ZWDeletdialog.vue';
import ZWCreateTag from '@/components/ZWCreateTag.vue';
import { userTagGroupAdd, userTagGroupUpdate, userTagGroupDel } from '@/api/employe/label';
import { startLoading, endLoading } from '@/utils/request';
import router from '@/router';
import bus from '@/utils/bus';
import { treeH, reSize } from '@/utils/utils';

const ruleFormRef = ref<InstanceType<typeof ElForm>>();
const treeRef = ref<InstanceType<typeof ElTree>>();
const emit = defineEmits(['submit']);
const groupData = defineProps(['userAllTagNameList']);
import { useStore } from '@/store';
const store = useStore();
const groupDialogRef = ref(null);
const treeHeight = ref<string>('660px');
interface Tree {
    id: number;
    name: string;
    children?: Tree[];
}

const selectId = ref(0);
const filterText = ref(''); // 搜索分组
const showEdit = ref(false); //是否展示部门编辑
const isUpdate = ref(false); //是否是编辑弹框
const firstId = ref(4);
// 取消按钮
const cancelHandel = () => {
    appDialog.visible = false;
    isUpdate.value = false;
    ruleFormRef.value.resetFields();
};
// 保存按钮
const submitHandel = () => {
    startLoading();
    try {
        ruleFormRef.value.validate(async (valid: any) => {
            if (valid) {
                isUpdate.value
                    ? await userTagGroupUpdate({
                          name: addGroupingForm.name,
                          group_id: selectId.value
                      })
                    : await userTagGroupAdd({
                          name: addGroupingForm.name
                      });
                ElMessage.success(`${isUpdate.value ? '更新' : '创建'}标签分组成功`);
                selectId.value = 0; // 新增分组之后默认选择全部分组
                emit('submit');
                cancelHandel();
            }
        });
    } catch (error) {
        endLoading();
    }
};
// 弹框相关配置
const appDialog = reactive({
    visible: false,
    title: `创建分组`,
    width: '500px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '保存'
});
// 添加分组表单
const addGroupingForm = reactive({
    name: '' // 添加分组名称
});
// 添加分组校验规则
const rules = reactive({
    name: [
        {
            required: true,
            message: '请填写分组名称',
            trigger: 'blur'
        }
    ]
});

const defaultProps = {
    checkStrictly: true,
    emitPath: false,
    label: 'name',
    value: 'id'
};

watch(filterText, val => {
    treeRef.value!.filter(val);
});
// 搜索分组
const filterNode = (value: string, data: Tree) => {
    if (!value) return true;
    return data.name.indexOf(value) !== -1;
};

//鼠标移入
const mouseOver = (data: any) => {
    // selectId.value = data.id
    data.showEdit = true;
};
//鼠标移出
const mouseLeave = (data: any) => {
    // selectId.value = 0
    data.showEdit = false;
};

//鼠标移入 tooltip
const mouseOver2 = (data: any) => {
    const ele = getElementByAttr('div', 'data-key', data.id);
    ele[0].getElementsByClassName('el-tree-node__content')[0].classList.add('tree-hover');
};
//鼠标移出 tooltip
const mouseLeave2 = (data: any) => {
    const ele = getElementByAttr('div', 'data-key', data.id);
    ele[0].getElementsByClassName('el-tree-node__content')[0].classList.remove('tree-hover');
};
// 根据data-key属性获取dom
const getElementByAttr = (tag: any, attr: any, value: any) => {
    const aElements = document.getElementsByTagName(tag);
    const aEle = [];
    for (let i = 0; i < aElements.length; i++) {
        if (aElements[i].getAttribute(attr) == value) aEle.push(aElements[i]);
    }
    return aEle;
};

//切换id
const changeData = (data: any) => {
    selectId.value = data.id;
    emit('submit', data);
    bus.emit('submit', data);
};

const nodeClick = (data: any, node: any) => {
    selectId.value = data.id;
    emit('submit', data);
    bus.emit('submit', data);

    // selectId.value = val.id;
    // emit('submit', val);
    // store.dispatch('setGroupId', val.id);
    // if (node.level == 1) {
    //     node.expanded = true;
    // }
    // nextTick(() => {
    //     treeRef.value?.setCheckedKeys([val.id], true);
    // });
};
let currentData = null;
// 新增/编辑分组的弹框
const addGroup = (flag: boolean, data?: any) => {
    appDialog.title = `${flag ? '更新' : '添加'}标签分组`;
    currentData = data;
    addGroupingForm.name = flag ? data.name : '';
    appDialog.visible = true;
    isUpdate.value = flag;
};
// 删除
const removeGroup = (data: any) => {
    currentData = data;
    groupDialogRef.value.appDialog.visible = true;
};
// 删除分组确认按钮
const delBtn = () => {
    startLoading();
    userTagGroupDel({
        group_id: currentData.id
    })
        .then((res: any) => {
            groupDialogRef.value.appDialog.visible = false;
            ElMessage.success(`删除分组成功`);
            // 如果是删除了当前选中的分组，则到默认分组
            if (selectId.value === currentData.id) {
                const groupList = groupData.userAllTagNameList?.[0]?.children || [];
                const defaultGroupItem = groupList.find(item => item?.name === '默认分组');
                if (defaultGroupItem) {
                    emit('submit', { id: defaultGroupItem.id });
                    selectId.value = defaultGroupItem.id;
                } else {
                    // 如果没有默认分组，则到全部分组（因为每个默认分组的id不一样需要按照名称查询才可以）
                    emit('submit', { id: 0 });
                    selectId.value = 0;
                }
                return;
            }

            emit('submit');
        })
        .catch(() => {
            endLoading();
        });
};

/**
 * @description: 获取tree高度
 * @return {*}
 */
const getTreeH = () => {
    const h = treeH('.tree-scrollbar');
    treeHeight.value = `${h}px`;
};

onMounted(() => {
    getTreeH();
    reSize(() => getTreeH());
});

defineExpose({
    selectId,
    getTreeH
});
</script>

<style lang="scss" scoped>
.layout {
    display: flex;

    .left-nav {
        width: 238px;
        border: 1px solid #eaeaea;
        background-color: #fff;
        justify-content: center;
        padding: 16px;
        margin-right: 16px;

        // box-shadow: 0px 0.5px 10px rgb(0 0 0 / 20%);
        .nav-title {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;

            .plus-icon {
                cursor: pointer;
            }
        }

        .nav-text {
            font-size: 16px;
            font-weight: 600;
            color: #33302d;
        }

        .nav-input {
            width: 238px;
            padding: 16px 0 20px;
        }

        .el-tree-node__content {
            height: 35px !important;
        }

        .hover-text {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .hover-detail {
                color: #535456;
                flex: 1;
                width: 0;
                font-size: 14px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }

            .hover-detail-color {
                color: #ff6b00;
                flex: 1;
                width: 0;
                font-size: 14px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }

            .hover-detail:hover {
                color: #ff6b00;
            }

            .hover-icon {
                transform: rotate(90deg);
            }
        }

        .search-list {
            display: flex;
            flex-direction: column;

            .search-detail {
                margin: 0;
                color: #33302d;
            }

            .search-detail:hover {
                background-color: #f5f7fa;
            }

            .hover-text {
                line-height: 35px;
            }
        }

        .no-data {
            display: flex;
            flex-direction: column;
            align-items: center;

            .nodata-img {
                margin: 30px 0 30px 15px;
                width: 150px;
                height: 120px;
            }
        }

        .groups {
            color: #33302d;
            font-size: 14px;

            .search_group {
                margin: 20px 0;
            }

            :deep(.el-tree) {
                --el-tree-node-hover-bg-color: #fffaf9;
            }

            :deep(.el-tree-node__content) {
                padding-right: 8px;

                &:hover {
                    background: #fffaf9;

                    .icon-span {
                        .hover-icon {
                            visibility: visible;
                        }
                    }

                    .hover-detail {
                        color: #ff6b00;
                    }
                }

                .icon-span {
                    padding-right: 4px;
                    display: flex;
                    align-items: center;

                    .hover-icon {
                        visibility: hidden;
                    }
                }
            }
        }

        :deep(.el-popper) {
            text-align: center !important;
        }
    }

    :deep(.tree-hover) {
        background: #fffaf9;

        .hover-detail-color {
            color: #ff6b00 !important;
        }

        .hover-detail {
            color: #ff6b00 !important;
        }

        .icon-span {
            .hover-icon {
                visibility: visible !important;
            }
        }
    }
}
</style>
